package com.ncmmall.application.business.coupon;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.marketing.coupon.Coupon;
import com.ncmmall.domain.business.marketing.coupon.CouponChannel;
import com.ncmmall.domain.business.marketing.coupon.CouponChannelRepository;
import com.ncmmall.domain.business.marketing.coupon.CouponGoods;
import com.ncmmall.domain.business.marketing.coupon.CouponGoodsRepository;
import com.ncmmall.domain.business.marketing.coupon.CouponMemberDraw;
import com.ncmmall.domain.business.marketing.coupon.CouponMemberDrawRepository;
import com.ncmmall.domain.business.marketing.coupon.CouponRepository;
import com.ncmmall.domain.business.marketing.coupon.QCoupon;
import com.ncmmall.domain.business.marketing.coupon.QCouponChannel;
import com.ncmmall.domain.business.marketing.coupon.QCouponGoods;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * @author linxs
 * @Description: 优惠券业务
 * @Date: 2019-10-24 12:00
 */
@Service
@Transactional
public class CouponApplication {

    @Autowired
    private CouponRepository couponRepository;

    @Autowired
    private CouponChannelRepository couponChannelRepository;

    @Autowired
    private CouponGoodsRepository couponGoodsRepository;

    @Autowired
    private CouponMemberDrawRepository memberDrawRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 修改优惠券信息
     */
    public void modify(Coupon params) {

        Coupon coupon = queryChannelService.findOne(QCoupon.coupon.id.eq(params.getId()), Coupon.class);
        coupon.setName(params.getName());
        coupon.setComplimentaryGoods(params.getComplimentaryGoods());
        coupon.setConditionAmount(params.getConditionAmount());
        coupon.setDenominationAmount(params.getDenominationAmount());
        coupon.setReleasedQuantity(params.getReleasedQuantity());
        coupon.setScopeType(params.getScopeType());
        coupon.setType(params.getType());
        coupon.setValidityBeginDay(params.getValidityBeginDay());
        coupon.setValidityEndDay(params.getValidityEndDay());
        coupon.setValidityDay(params.getValidityDay());
        coupon.setValidityType(params.getValidityType());
        coupon.setChannelData(params.getChannelData());
        coupon.setGoodsesData(params.getGoodsesData());

        couponRepository.save(coupon);

        couponChannelRepository.delete(queryChannelService.findAll(QCouponChannel.couponChannel.coupon.id.eq(params.getId()), CouponChannel.class));
        couponGoodsRepository.delete(queryChannelService.findAll(QCouponGoods.couponGoods.coupon.id.eq(params.getId()), CouponGoods.class));

        List<String> channelsIds = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(coupon.getChannelData());
        for (String channelsId : channelsIds) {
            CouponChannel channel = new CouponChannel();
            channel.setCoupon(coupon);
            channel.setChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(Long.parseLong(channelsId)), GoodsChannel.class));
            couponChannelRepository.save(channel);
        }

        List<String> goodsesData = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(coupon.getGoodsesData());
        for (String goodsId : goodsesData) {
            CouponGoods goods = new CouponGoods();
            goods.setCoupon(coupon);
            goods.setGoods(queryChannelService.findOne(QGoods.goods.id.eq(Long.parseLong(goodsId)), Goods.class));
            couponGoodsRepository.save(goods);
        }
    }

    /**
     * 提交申请审核
     */
    public void applyProcess(Coupon coupon) {
        coupon.setStatus(4);
        couponRepository.save(coupon);
    }

    /**
     * 批量上架
     */
    public void putaways(List<Coupon> coupons) {
        for (Coupon coupon : coupons) {
            Requires.isTrue(coupon.getStatus() == 2, "未审核通过的优惠券无法上架");
            coupon.setPublishStatus(2);
        }
        couponRepository.save(coupons);
    }

    /**
     * 批量下架
     */
    public void soldoutss(List<Coupon> transform) {
        for (Coupon coupon : transform) {
            soldout(coupon);
        }
    }

    /**
     * 下架
     */
    public void soldout(Coupon coupon) {
        coupon.setPublishStatus(1);
        couponRepository.save(coupon);
    }

    /**
     * 创建优惠券
     */
    public void create(Coupon coupon) {

        coupon.setCreateTime(new Timestamp(System.currentTimeMillis()));
        coupon.setStatus(1);
        coupon.setChoiceStatus(1);
        coupon.setPublishStatus(1);
        couponRepository.save(coupon);

        List<String> channelsIds = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(coupon.getChannelData());
        for (String channelsId : channelsIds) {
            CouponChannel channel = new CouponChannel();
            channel.setCoupon(coupon);
            channel.setChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(Long.parseLong(channelsId)), GoodsChannel.class));
            couponChannelRepository.save(channel);
        }

        List<String> goodsesData = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(coupon.getGoodsesData());
        for (String goodsId : goodsesData) {
            CouponGoods goods = new CouponGoods();
            goods.setCoupon(coupon);
            goods.setGoods(queryChannelService.findOne(QGoods.goods.id.eq(Long.parseLong(goodsId)), Goods.class));
            couponGoodsRepository.save(goods);
        }

    }

    /**
     * 删除优惠券
     */
    public void remove(Coupon coupon) {
        couponRepository.delete(coupon);
    }

    /**
     * 上架
     */
    public void putaway(Coupon coupon) {
        Requires.isTrue(coupon.getStatus() == 2, "未审核通过的优惠券无法上架");
        coupon.setPublishStatus(2);
        couponRepository.save(coupon);
    }

    /**
     * 审核优惠券
     */
    public void process(Coupon params) {
        Coupon coupon = queryChannelService.findOne(QCoupon.coupon.id.eq(params.getId()), Coupon.class);
        coupon.setStatus(params.getStatus());
        coupon.setNote(params.getNote());
        couponRepository.save(coupon);
    }

    /**
     * 取消精选优惠券
     */
    public void cancelChoice(Coupon params) {
        Coupon coupon = queryChannelService.findOne(QCoupon.coupon.id.eq(params.getId()), Coupon.class);
        coupon.setChoiceStatus(1);
        couponRepository.save(coupon);
    }

    /**
     * 设置精选优惠券
     */
    public void choice(Coupon params) {
        Coupon coupon = queryChannelService.findOne(QCoupon.coupon.id.eq(params.getId()), Coupon.class);
        coupon.setChoiceStatus(2);
        couponRepository.save(coupon);
    }

    /**
     * 领取优惠券
     */
    public CouponMemberDraw draw(WebUser member, Coupon coupon) {

        CouponMemberDraw memberDraw = new CouponMemberDraw();
        memberDraw.setMember(member);
        memberDraw.setCoupon(coupon);
        memberDraw.setStatus(1);

        if (coupon.getValidityType() == 2) {
            DateTime dateTime = DateUtil.offsetDay(new Date(), coupon.getValidityDay());
            memberDraw.setExpirationTime(dateTime.toTimestamp());
        } else {
            memberDraw.setExpirationTime(DateUtil.parseDate(coupon.getValidityEndDay()).toTimestamp());
        }

        memberDraw.setDrawTime(new Timestamp(System.currentTimeMillis()));
        memberDrawRepository.save(memberDraw);

        coupon.setDrawQuantity(coupon.getDrawQuantity() + 1);
        if (coupon.getDrawQuantity() >= coupon.getReleasedQuantity()) {
            coupon.setStatus(5);
            coupon.setPublishStatus(1);
        }
        couponRepository.save(coupon);

        return memberDraw;
    }

    /**
     * 优惠券定时过期
     */
    public void autoCoupon() {
        List<Coupon> coupons = queryChannelService.queryAllEntity("select * FROM mall_coupon where validityEndDay is not null and validityEndDay != '' and  validityEndDay < date(now()) and publishStatus = 2", ImmutableMap.of(), Coupon.class);
        for (Coupon coupon : coupons) {
            coupon.setPublishStatus(1);
            couponRepository.save(coupon);
        }
        List<CouponMemberDraw> couponMemberDraws = queryChannelService.queryAllEntity("select * FROM mall_coupon_member_draw where date(expirationTime) < date(now()) and status != 3", ImmutableMap.of(), CouponMemberDraw.class);
        for (CouponMemberDraw memberDraw : couponMemberDraws) {
            memberDraw.setStatus(3);
            memberDrawRepository.save(memberDraw);
        }
    }
}
